<?php

namespace App\Admin\Controllers\Articles;

use App\Models\Article;
use App\Models\Module;
use App\Models\Country;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;


class AllArticleController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     *
     * 通过添加一个查询参数例如/articles?module={id} 能获取到某个分类的资讯
     */
    public function index(Request $request)
    {
        $id = $request->query('module');
        return Admin::content(function (Content $content) use ($id) {

            if ($id != null) {
                $title = Module::where('id', $id) -> first() -> title;
                $content->header($title);
            }else{
                $content->header('资讯管理');
            }
            $content->body($this->grid($id));
        });
    }


    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('资讯管理');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('资讯管理');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($id)
    {
        return Admin::grid(Article::class, function (Grid $grid) use ($id){

            $grid->disableExport();
            if ($id != null){
              $grid->model()->where('module_id', $id);
            }
            $grid->id('ID');
            $grid->order('排序')->editable();
            $grid->title('标题')->editable();
            $grid->picture('头图')->image();
            $grid->module()->title('模块')->label();
            $grid->updated_at('更新时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Article::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->number('order', '排序');
            $form->text('title', '标题')->rules('required');
            $form->editor('content', '内容');
            $form->image('picture', '头图')->removable()->help(
              '轮播图时1242*546，猜你喜欢150*150，热门资讯240*180'
            );
            $form->select('module_id', '分类')->options(Module::all()->pluck('title', 'id'));
            $form->multipleSelect('countries', '国家')->options(Country::all()->pluck('title', 'id'));
            $form->display('created_at', '创建时间');
            $form->display('updated_at', '更新时间');

            $form->saved(function (Form $form) {
                try{
                    $content = strip_tags($form->model()->content);
                    $result = $this->send_boson($content);
                    $form->model()->keyword = $result;
                    $form->model()->save();
                } catch (\Exception $e){
                    Log::error($e);
                }

            });
        });
    }

    protected function send_boson($content){
        $client = new Client([
            'base_uri' => config('services.boson')['keyword_url'],
            'timeout'  => 2.0,
            'headers' => ['Content-Type'  => 'application/json',
                            'Accept' => 'application/json',
                        'X-Token' => config('services.boson')['key']
                        ],
        ]);
        $res_content = $client->post(config('services.boson')['keyword_url'],
            ['body' => json_encode($content)]
            );
        $res_content = json_decode($res_content->getBody(), True);
        $result = array();
        foreach ($res_content as $content){
            array_push($result, $content[1]);
        }
        return implode(",", $result);
    }
}
